!function(e,w){
	function TOS(options){
		Object.assign(this,{
			contextMenuArea: e.querySelector("#context-menu-area"),
			startBtn: e.querySelector("#statusBar .start"),
			statusBar: e.querySelector("#statusBar"),
			desktopGrid: e.querySelector("#grid"),
			desktop: e.querySelector("#desktop"),
			taskBar: e.querySelector("#tasks"),
			timeH: e.querySelector("#clock .h"),
			timeY: e.querySelector("#clock .y"),
			openWindows: [],
			tasks: [],
			currTask: "",
			defaultWindowPos: [120,120],
			defaultWindowSize: [400,400],
			defaultWindowTemplate: "",
			confirmWindowTemplate: "",
			listWindowTemplate: "",
			contextMenu: null,
			fileTree: null,
			currWindow: null,
			currFile: null,
			mainClock: null,
			isDrag: false,
			mainWidth: w.innerWidth,
			mainHeight: w.innerHeight,
			_startPos: [],
			_mousePos: [],
			fTypes: ["list","txt","disk"],
			loading: 0,
			theme: "lighter"
		},options)
		this.init()
	}
	TOS.prototype = {
		onload(){
			// 打开新窗口
			// setTimeout(() => {
			// 	this.open({
			// 		path: "c/desktop/welcome.txt",
			// 		pos: [100,100],
			// 		size: [300,300]
			// 	})
			// },1000)
			// setTimeout(() => {
			// 	this.open({
			// 		path: "c/desktop",
			// 		pos: [20,240],
			// 		size: [500,400],
			// 		// maxsize: true
			// 	})
			// },800)
			
			setTimeout(() => {
				this.createContextMenu(220,220,"window")
			},200)
			
			// this.confirm({
			// 	title: "主题选择",
			// 	confirmText: "是否切换至暗夜主题？",
			// 	success: () => {
			// 		this.changeTheme("dark")
			// 	}
			// })
			this.changeTheme("dark")
		},
		init(){
			this.addEvents()
			this.initTemplates()
			this.initFileTree().then(this.initDesktop.bind(this))
			this.initContextMenu()
			this.initTaskBar()
			this.initClock()
		},
		// 初始化时钟
		initClock(){
			this.mainClock = setInterval(() => {
				let date = new Date()
				let yy = date.getFullYear()
				let mm = date.getMonth()+1
				let dd = date.getDate()
				let hh = date.getHours()
				let nn = date.getMinutes()
				let ss = date.getSeconds()
				ss = ss < 10 ? "0" + ss : ss
				let h = `${hh}:${nn}:${ss}`
				let y = `${yy}/${mm}/${dd}`
				this.timeH.innerText = h
				this.timeY.innerText = y
			},500)
		},
		addEvents(){
			e.oncontextmenu = evt => {
				evt.preventDefault()
			}
			e.onmousemove = evt => {
				if(evt.target.classList.contains("top-bar")){
					evt.preventDefault()
				}
			}
			w.onresize = evt => {
				this.mainWidth = w.innerWidth
				this.mainHeight = w.innerHeight
			}
		},
		// 初始化桌面
		initDesktop(){
			let str = this.createFiles("c/desktop")
			let g = this.desktopGrid
			g.innerHTML = str
			g.path = "c/desktop"
			g.type = "window"
			this.openWindows.push(g)
			this.currWindow = g
			g.onmousedown = evt => {
				let tars = Array.from(this.desktopGrid.children)
				let tar = evt.target.parentNode
				tars.forEach(t => {
					t.classList.remove("selected-dark")
				})
				if(tar.classList.contains("file")){
					tar.classList.add("selected-dark")
				}else if(tar.id == "desktop"){
					// console.log("点击了桌面")
					this.currWindow = g
					this.actWindowMaster()
				}
			}
			g.ondblclick = evt => {
				let tar = evt.target.parentNode
				if(tar.classList.contains("file")){
					let link = tar.getAttribute("link")
					link && this.open(link)
				}
			}
			// 任意处右击
			this.desktop.onmouseup = evt => {
				if(event.button === 2){
					let tar = evt.target
					let type = ""
					if(tar === this.desktopGrid){
						type = "window"
					}else if(tar.closest(".file") && tar.closest(".file").getAttribute("link")){
						this.currFile = tar.closest(".file").getAttribute("link")
						type = "file"
					}else if(tar.closest(".wd")){
						type = "window"
					}
					if(tar.closest("#grid")){
						this.currWindow = this.desktopGrid
					}
					if(tar.classList.contains("pc")){
						type = "pc"
					}
					this.actWindowMaster()
					this.createContextMenu(evt.pageX,evt.pageY,type)
				}
			}
			this.desktop.onclick = evt => {
				this.contextMenuArea.innerHTML = ""
			}
		},
		// 刷新当前窗口, 可选刷新指定窗口
		refresh(userWd){
			let wd = userWd ? userWd : this.currWindow
			if(wd === this.desktopGrid){
				wd.innerHTML = this.createFiles(wd.path)
			}else{
				let str = this.createFiles(wd.route[wd.route["currIndex"]])
				wd.querySelector(".content").innerHTML = str
			}
			let fileEls = Array.from(wd.querySelectorAll(".file-name"))
			fileEls.forEach(f => {
				f.classList.add("inline")
			})
		},
		// 新窗口出生位置管理
		windowPositionMaster(){
			this.defaultWindowPos[0] += 50
			this.defaultWindowPos[1] += 20
			if(this.defaultWindowPos[0] > this.mainWidth - 400){
				this.defaultWindowPos[0] = 0
			}
			if(this.defaultWindowPos[1] > this.mainHeight - 400){
				this.defaultWindowPos[1] = 0
			}
		},
		// 打开窗口核心方法
		open(obj){
			// 处理配置
			const option = {}
			/* 配置项展示
			const option = {
				path: "",
				type: "confirm" / "txt" / "list" / "unknown",
				confirmText: "",
				pos: [0,0],
				size: [400,400],
				maxsize: false
			}
			*/
			if(typeof obj === "object" && obj !== null){
				Object.assign(option,obj)
			}else if(typeof obj === "string"){
				option.path = obj
			}else{
				return
			}
			if(!option.type){
				var file = this.findFile(option.path)
				option.type = file.type
				if(option.type == "unknown"){
					this.confirm("未知文件类型，请检查文件后缀名")
					return
				}
			}
			if(option.type == "pc"){
				option.path = "/"
			}
			// 创建窗口
			let wd = e.createElement("div")
			// 注册窗口
			this.openWindows.push(wd)
			this.currWindow = wd
			// 窗口获取焦点
			this.actWindowMaster()
			// 设置属性
			wd.zIndex = this.openWindows.length
			wd.style.zIndex = wd.zIndex
			wd.wdId = Date.now()
			wd.isMaxsize = false
			wd.setAttribute("wd-id",wd.wdId)
			wd.route = [option.path] // 路由栈
			wd.route.currIndex = 0 // 当前页在路由栈内的索引
			wd.isStart = true // 当前页是否在路由始端
			wd.isEnd = true // 当前页是否在路由末端
			wd.path = option.path
			wd.className = option.type + "-wd wd act"
			wd.isHidden = false
			wd.handleMinisize = () => {
				wd.isHidden = true
				wd.style.display = "none"
				this.currWindow = this.openWindows[this.openWindows.length-2]
				// console.log(this.currWindow)
				this.actWindowMaster()
			}
			wd.handleMaxsize = () => {
				// console.log(wd)
				wd.isMaxsize = true
				wd.isHidden = false
				wd.style.display = "block"
				wd.preStatus = {
					pos: [wd.offsetLeft,wd.offsetTop],
					size: [wd.offsetWidth,wd.offsetHeight]
				}
				wd.style.left = 0
				wd.style.top = 0
				wd.style.width = "100%"
				wd.style.height = "100%"
				resizeBtn.classList.remove("maxsize")
				resizeBtn.setAttribute("type","resize")
			}
			wd.handleResize = () => {
				wd.isHidden = false
				wd.isMaxsize = false
				wd.style.display = "block"
				wd.style.left = wd.preStatus.pos[0] + "px"
				wd.style.top = (wd.preStatus.pos[1] < 0 ? 0 : wd.preStatus.pos[1]) + "px"
				wd.style.width = wd.preStatus.size[0] + "px"
				wd.style.height = wd.preStatus.size[1] + "px"
				resizeBtn.classList.add("maxsize")
				resizeBtn.setAttribute("type","maxsize")
			}
			// 加载内容
			if(option.type == "confirm"){
				wd.innerHTML = this.confirmWindowTemplate
				var confirmTextEl = wd.querySelector(".confirm-text")
				var titleEl = wd.querySelector(".title")
				confirmTextEl.innerText = option.confirmText
				option.title && (titleEl.innerText = option.title)
			}else{
				if(option.type == "txt"){
					wd.innerHTML = this.defaultWindowTemplate
				}else if(option.type == "list" || option.type == "pc" || option.type == "disk"){
					wd.innerHTML = this.listWindowTemplate
				}
				if(option.path){
					var content = wd.querySelector(".content")
					var topBar = wd.querySelector(".top-bar .title")
					var resizeBtn = wd.querySelector(".resize")
					if(option.type == "txt"){
						topBar.innerText = option.path
						content.innerText = file.content
						content.oninput = evt => {
							evt.currentTarget.isChange = true
						}
					}else if(option.type == "list" || option.type == "pc" || option.type == "disk"){
						topBar.innerText = option.path == "/" ? "TOS" : option.path + "/"
						content.innerHTML = this.createFiles(option.path,file)
					}
					resizeBtn.classList.add("maxsize")
					resizeBtn.setAttribute("type","maxsize")
				}
				wd.style.left = option.pos ? option.pos[0] + "px" : this.defaultWindowPos[0] + "px"
				wd.style.top = option.pos ? option.pos[1] + "px" : this.defaultWindowPos[1] + "px"
				wd.style.width = option.size ? option.size[0] + "px" : this.defaultWindowSize[0] + "px"
				wd.style.height = option.size ? option.size[1] + "px" : this.defaultWindowSize[1] + "px"
				this.windowPositionMaster()
				// 初始最大化
				option.maxsize && wd.handleMaxsize()
			}
			setTimeout(() => {
				wd.preStatus = {
					pos: [wd.offsetLeft,wd.offsetTop],
					size: [wd.offsetWidth,wd.offsetHeight]
				}
			})
			this.desktop.appendChild(wd)
			// 为任务栏添加图标
			this.tasks.push({
				static: false,
				type: option.type,
				running: true,
				act: true,
				id: wd.wdId
			})
			this.refreshTaskBar()
			// 注册按钮单击事件
			wd.onclick = evt => {
				let curr = evt.currentTarget
				let tar = evt.target.parentNode
				let contentEl = curr.querySelector(".content")
				let type = evt.target.getAttribute("type")
				if(type == "minisize"){ // 最小化
					console.log("minisize")
					curr.handleMinisize()
				}else if(type == "maxsize"){ // 最大化
					curr.handleMaxsize()
				}else if(type == "resize"){ // 还原
					curr.handleResize()
				}else if(type == "close"){ // 关闭
					this.close(curr.wdId)
				}else if(type == "save"){
					file.content = contentEl.value
					contentEl.isChange = false
				}else if(type == "back" || type == "proceed"){
					if(type == "back"){
						if(!wd.isStart){ // 不在开头才能后退
							this.navBack(true)
						}
					}else{
						if(!wd.isEnd){ // 不在末尾才能前进
							this.navBack()
						}
					}
				}
				if(tar.classList.contains("file")){
					let tars = Array.from(tar.parentNode.children)
					tars.forEach(t => {
						t.classList.remove("selected")
					})
					tar.classList.add("selected")
				}
			}
			// 注册鼠标按下事件
			wd.onmousedown = evt => {
				let curr = evt.currentTarget
				let target = evt.target
				// 窗口层级管理
				this.currWindow = curr
				this.zIndexMaster(curr)
				this.actWindowMaster()
				if(target.classList.contains("top-bar")){ // 拖拽移动窗口
					this.isDrag = true
					this._startPos = [curr.offsetLeft,curr.offsetTop]
					this._mousePos = [evt.pageX,evt.pageY]
					this.topBarMouseMove = evt => {
						if(this.isDrag){
							let c = this.currWindow
							c.isMaxsize && c.handleResize()
							c.style.left = this._startPos[0] + evt.pageX - this._mousePos[0] + "px"
							c.style.top = this._startPos[1] + evt.pageY - this._mousePos[1] + "px"
						}
					}
					this.topBarMouseUp = evt => {
						this.isDrag && (this.isDrag = false)
						curr.preStatus = {
							pos: [wd.offsetLeft,wd.offsetTop],
							size: [wd.offsetWidth,wd.offsetHeight]
						}
						if(evt.pageY < 10){
							this.currWindow.handleMaxsize()
						}
						w.removeEventListener("mousemove",this.topBarMouseMove)
						w.removeEventListener("mouseup",this.topBarMouseUp)
					}
					w.addEventListener("mousemove",this.topBarMouseMove)
					w.addEventListener("mouseup",this.topBarMouseUp)
				}
			}
			// 注册按钮双击事件: 打开文件 / 文件夹
			wd.ondblclick = evt => {
				let wd = evt.currentTarget
				let tar = evt.target.parentNode
				let link = tar.getAttribute("link")
				if(link){
					this.navTo(link,wd)
				}
			}
			return wd
		},
		// 弹出确认框(接受三个钩子函数)
		confirm(obj){
			const option = {
				confirmText: "提示信息",
				success(){}, // 点击确认触发
				fail(){}, // 点击取消触发
				complete(){} // 点击任意按钮后触发
			}
			if(typeof obj === "object" && obj !== null){
				Object.assign(option,obj)
			}else if(typeof obj === "string"){
				option.confirmText = obj
			}
			let wd = this.open({
				type: "confirm",
				confirmText: option.confirmText,
				title: option.title
			})
			wd.style.left = this.mainWidth / 2 - wd.offsetWidth / 2 + "px"
			let clickEvent = evt => {
				if(evt.target.classList.contains("btn")){
					let type = evt.target.getAttribute("type")
					if(type == "yes" || type == "no"){
						wd.removeEventListener("click",clickEvent)
						wd.remove()
						this.openWindows.pop()
						this.currWindow = this.openWindows[this.openWindows.length-1]
						;(type == "yes") && option.success()
						;(type == "no") && option.fail()
						option.complete(wd.wdId)
						this.closeTask(wd.wdId)
					}
				}
			}
			wd.addEventListener("click",clickEvent)
		},
		close(wdId){
			let curr = this.openWindows.find(wd => wd.wdId == wdId)
			let contentEl = curr.querySelector(".content")
			if(contentEl && contentEl.isChange){
				// 弹窗提示保存
				let file = this.findFile(curr.path)
				this.confirm({
					confirmText: "当前文件尚未保存，关闭前是否保存？",
					success: () => {
						file.content = contentEl.value
						curr.remove()
					},
					fail: () => {
						curr.remove()
					},
					complete: wdId => {
						this.openWindows.pop()
						this.currWindow = this.openWindows[this.openWindows.length-1]
						this.actWindowMaster()
						this.closeTask(curr.wdId) // 移除文本编辑窗口
						this.refreshTaskBar()
					}
				})
			}else{
				curr.remove()
				this.openWindows.pop()
				this.currWindow = this.openWindows[this.openWindows.length-1]
				this.actWindowMaster()
				this.closeTask(wdId)
				this.refreshTaskBar()
			}
		},
		// 窗口内跳转
		navTo(path,wd){
			var file = this.findFile(path)
			if(file.type == "disk" || file.type == "list"){
				if(!wd){
					console.log("必须指定窗口 dom 对象！")
					return
				}
				// 抛弃当前页面之后的路由栈项
				for(let i = 0; i < wd.route.length - wd.route.currIndex - 1; i++){
					wd.route.pop()
				}
				wd.route.push(path)
				wd.route.currIndex++
				wd.path = wd.route[wd.route.currIndex]
				this.checkNav()
				var content = wd.querySelector(".content")
				var topBar = wd.querySelector(".top-bar .title")
				content.innerHTML = this.createFiles(path)
				topBar.innerText = path
			}else{
				this.open(path)
			}
		},
		// 窗口内返回 / 前进
		navBack(isBack){
			var wd = this.currWindow
			var content = wd.querySelector(".content")
			var topBar = wd.querySelector(".top-bar .title")
			var path = isBack ? wd.route[--wd.route.currIndex] : wd.route[++wd.route.currIndex]
			wd.path = path
			this.checkNav()
			content.innerHTML = this.createFiles(path)
			topBar.innerText = path
		},
		// 检查路径位于路由的索引, 变更进退按钮样式
		checkNav(){
			var wd = this.currWindow
			// 当前页所在路由栈中位置判断
			wd.isStart = false
			wd.isEnd = false
			if(wd.route.currIndex === wd.route.length - 1 && wd.route.currIndex !== 0){
				wd.isEnd = true
			}else if(wd.route.currIndex === 0 && wd.route.length > 1){
				wd.isStart = true
			}
			var backBtn = wd.querySelector(".back")
			var proceedBtn = wd.querySelector(".proceed")
			backBtn.classList[wd.isStart ? 'remove' : 'add']("act")
			proceedBtn.classList[wd.isEnd ? 'remove' : 'add']("act")
		},
		// 窗口焦点(激活状态)管理
		actWindowMaster(){
			this.openWindows.forEach(wn => {
				wn.classList.remove("act")
			});
			(this.openWindows.length > 0) && this.currWindow.classList.add("act")
			this.taskMaster()
		},
		// 窗口层级管理
		zIndexMaster(curr){
			if(curr !== this.desktopGrid){
				let currIndex = this.openWindows.findIndex(wn => wn === curr)
				this.openWindows.splice(currIndex,1)
				this.openWindows.push(curr)
				this.openWindows.forEach((wn,i) => {
					wn.style.zIndex = i + 1
				})
			}
		},
		// 任务栏管理
		taskMaster(){
			// {
			// 	static: false,
			// 	type: option.type,
			// 	running: true,
			// 	act: true,
			// 	id: wd.wdId
			// }
			this.tasks.forEach(t => {
				t.act = t.id == this.currWindow.wdId
			})
			this.zIndexMaster(this.currWindow)
			this.refreshTaskBar()
		},
		// 创建右键菜单
		createContextMenu(x,y,menuType){
			this.contextMenuArea.innerHTML = ""
			if(this.contextMenu.length == 0){
				return false
			}
			let isRoot = true
			let _menu = (parentNode,cArr) => {
				if(!cArr){
					throw new Error("Unknown context menu type ！")
				}
				let m = e.createElement("div")
				if(isRoot){
					m.className = "context-menu root-menu"
					m.style.left = x + "px"
					m.style.top = y + "px"
				}else{
					m.className = "context-menu sub"
				}
				parentNode.appendChild(m)
				isRoot = false
				cArr.forEach(ch => {
					let mItem = e.createElement("div")
					mItem.className = "menu-item isHidden"
					mItem.innerText = ch.name
					ch.type && (mItem.type = ch.type)
					m.appendChild(mItem)
					if(ch.children){
						mItem.classList.add("has-ch")
						_menu(mItem,ch.children)
					}
				})
				return m
			}
			let m = _menu(this.contextMenuArea,this.contextMenu[menuType])
			// 靠屏幕右缘右击弹窗位置校准
			if(this.mainWidth - m.offsetLeft < 200){
				m.style.left = x - 200 + "px"
			}
			if(menuType == "task"){
				m.style.top = y - m.offsetHeight + "px"
			}
		},
		// 为右键菜单添加处理函数
		initContextMenu(){
			return new Promise((resolve,reject) => {
				this.get("system/options/contextMenu.json").then(res => {
					this.contextMenu = res
					resolve()
				})
				this.contextMenuArea.onclick = evt => {
					let tar = evt.target
					if(tar.classList.contains("menu-item")){
						let type = tar.type
						// console.log(type)
						// 执行...
						if(type === "refresh"){
							this.refresh()
						}else if(type === "createFiles"){
							this.createFile("list","新建文件夹")
						}else if(type === "createTxt"){
							this.createFile("txt","新建文本")
						}else if(type === "sub-menu"){
							this.confirm({
								confirmText: "是否创建二次元异世界入口？",
								success: () => {
									setTimeout(() => {
										this.confirm({
											confirmText: "创建成功，是否进入？",
											success: () => {
												w.location = "https://www.bilibili.com"
											}
										})
									},500)
								}
							})
						}else if(type === "open"){
							this.open(this.currFile)
						}else if(type === "del"){
							this.confirm({
								confirmText: "是否删除"+this.currFile+"?",
								success: () => {
									this.delFile()
								}
							})
						}else if(type === "rename"){
							let opraFile = this.findFile(this.currFile) // 修改 opraFile.name
							this.rename()
						}else if(type === "close"){
							this.close(this.currTask)
						}else if(type === "change-theme-lighter"){
							this.changeTheme("lighter")
						}else if(type === "change-theme-dark"){
							this.changeTheme("dark")
						}else if(type === "change-theme-anime"){
							this.changeTheme("anime")
						}
						if(!tar.classList.contains("has-ch")){
							this.contextMenuArea.innerHTML = ""
						}
					}
				}
			})
		},
		// 渲染文件列表
		createFiles(path){
			var file = this.findFile(path)
			let str = ""
			if(file.children && file.children[0]){
				file.children.forEach(ch => {
					if(ch.type == "pc"){
						str += `<div class="file" link="/"><div class="file-icon ${ ch.type }"></div><div class="file-name inline">${ ch.name }</div></div>`
					}else if(ch.type == "disk"){
						str += `<div class="file" link="${ ch.name }"><div class="file-icon ${ ch.type }"></div><div class="file-name inline">${ ch.name }</div></div>`
					}else{
						str += `<div class="file" link="${ path }/${ ch.name }"><div class="file-icon ${ ch.type }"></div><div class="file-name inline">${ ch.name }</div></div>`
					}
				})
			}
			return str
		},
		// 新建文件
		createFile(type,name){
			let root = this.findFile(this.currWindow.path)
			name = this.beforeRename(name)
			if(type === "list"){
				root.children.push({name,type,children:[]})
			}else if(type === "txt"){
				root.children.push({name,type,content:""})
			}
			this.refresh(this.currWindow)
		},
		// 检查目录下是否有重名文件(夹)
		checkFileName(root,name){
			let resIndex = (root.findIndex && root.findIndex(ch => ch.name === name))
			if(resIndex === -1){
				return true
			}
			return false
		},
		// 重命名前的文件名管理钩子(重名主动添加序号)
		beforeRename(name){
			let root = this.findFile(this.currWindow.path)
			let tempName = name
			let count = 0
			while(!this.checkFileName(root.children,tempName)){
				tempName = `${ name } (${ ++count })`
			}
			return tempName
		},
		// 重命名
		rename(){
			let _this = this
			let currWdContent,currDomChs,path = this.currWindow.path
			if(this.currWindow === this.desktopGrid){
				currWdContent = this.desktopGrid
			}else{
				currWdContent = this.currWindow.querySelector(".content")
			}
			currWdContent && (currDomChs = Array.from(currWdContent.children))
			let index = this.findFile(path).children.findIndex(ch => ch.name == this.getFileNameFromPath(this.currFile))
			// console.log(currDomChs[index]) // 单文件 dom
			// console.log(this.findFile(this.currFile)) // 文件对象
			// let tempType = this.getFileTypeFromPath(currDomChs[index].getAttribute("link"))
			let nameEl = currDomChs[index].querySelector(".file-name")
			let inputEl = e.createElement("input")
			inputEl.className = "file-name-input"
			currDomChs[index].appendChild(inputEl)
			inputEl.focus()
			inputEl.value = nameEl.innerText
			nameEl.remove()
			inputEl.onkeydown = function() {
				if(event.key == "Enter"){
					this.onblur()
				}
			}
			inputEl.onblur = function() {
				let name
				if(_this.findFile(_this.currFile).name === this.value){
					name = this.value
				}else{
					name = _this.beforeRename(this.value) // 检查重名
				}
				let newNameEl = e.createElement("div")
				let type = _this.getFileTypeFromPath(name)
				if(!_this.fTypes.find(f => f == type)){
					type = "unknown"
				}
				newNameEl.className = "file-name"
				newNameEl.innerText = name
				let fileOrigin = _this.findFile(_this.currFile) // 更新文件树
				fileOrigin.name = name
				fileOrigin.type = type
				// if(type == "list"){
				// 	fileOrigin.children = fileOrigin.children ? fileOrigin.children : []
				// }
				// 修改于 2022/2/17
				if(type == "list" && !fileOrigin.children){
					fileOrigin.children = []
				}
				currDomChs[index].appendChild(newNameEl)
				currDomChs[index].setAttribute("link",_this.getParentPath(currDomChs[index].getAttribute("link"))+"/"+name)
				this.onblur = null
				this.remove()
				_this.refresh()
			}
		},
		// 删除文件(夹)
		delFile(){
			let currWd = this.currWindow
			let siblings = this.findFile(this.getParentPath(this.currFile)).children
			let index = siblings.findIndex(ch => ch.name == this.getFileNameFromPath(this.currFile))
			siblings.splice(index,1)
			this.refresh(currWd)
		},
		// 根据路径获取文件名
		getFileNameFromPath(path){
			let arr = path.split("/")
			return arr[arr.length-1]
		},
		// 根据路径获取文件类型(无后缀识别为list(文件夹))
		getFileTypeFromPath(path){
			let arr = path.split("/")
			let last = arr[arr.length-1].split(".")
			if(last.length === 1){
				return "list"
			}else{
				return last[last.length-1]
			}
		},
		// 根据路径获取上一级路径
		getParentPath(path){
			let arr = path.split("/")
			arr.pop()
			return arr.join("/")
		},
		// 初始化任务栏
		initTaskBar(){
			this.refreshTaskBar()
			this.taskBar.onmousedown = evt => {
				if(evt.button == 0){
					if(evt.target.classList.contains("task-icon")){
						let wdId = evt.target.getAttribute("wdId")
						let index = this.openWindows.findIndex(wd => wd.wdId == wdId)
						let wd = this.openWindows[index]
						if(wd.isHidden){
							if(wd.isMaxsize){
								wd.handleMaxsize()
							}else{
								wd.handleResize()
							}
						}else{
							if(wd === this.currWindow){
								wd.handleMinisize()
							}else{
								this.zIndexMaster(wd)
							}
						}
						this.currWindow = this.openWindows.find(wd => wd.wdId == wdId)
						this.actWindowMaster()
					}
				}else if(evt.button == 2){
					if(evt.target.classList.contains("task-icon")){
						let wdId = evt.target.getAttribute("wdId")
						let index = this.openWindows.findIndex(wd => wd.wdId == wdId)
						let wd = this.openWindows[index]
						this.createContextMenu(evt.pageX,evt.pageY,"task")
						this.currTask = wdId
					}
				}
			}
		},
		refreshTaskBar(){
			let arr = []
			this.tasks.forEach(t => {
				if(t.running || t.static){
					arr.push(`<div wdId="${t.id}" class="task-icon ${t.type} ${t.running?'running':''} ${t.act?'act':''}"></div>`)
				}
			})
			this.taskBar.innerHTML = arr.join("")
		},
		closeTask(wdId){
			let index = this.tasks.findIndex(t => t.id == wdId)
			if(index !== -1){
				this.tasks.splice(index,1)
				this.refreshTaskBar()
			}
			
		},
		// 初始化模板
		initTemplates(){
			this.get("system/templates/defaultWindow.txt").then(res => {
				this.defaultWindowTemplate = res
			})
			this.get("system/templates/confirmWindow.txt").then(res => {
				this.confirmWindowTemplate = res
			})
			this.get("system/templates/listWindow.txt").then(res => {
				this.listWindowTemplate = res
			})
		},
		// 初始化文件树
		initFileTree(){
			return new Promise((resolve,reject) => {
				this.get("system/options/defaultFileTree.json").then(res => {
					this.fileTree = res.fileTree
					resolve()
				})
			})
		},
		// 根据路径寻找文件对象
		findFile(path){
			if(path == "/"){
				return {
					name: "TOS",
					type: "pc",
					children: this.fileTree
				}
				return this.fileTree
			}
			let file = null
			let paths = path.split("/")
			let depth = 0
			let found = false
			let find = arr => {
				let res = arr.find(item => item.name === paths[depth])
				if(res){
					depth++
					if(paths.length === depth){
						found = true
						file = res
						return
					}else if(res.children){
						find(res.children)
					}else{
						throw new Error("路径"+path+"不存在！")
					}
				}else{
					throw new Error("路径"+path+"不存在！")
				}
			}
			find(this.fileTree)
			return file
		},
		// 请求本地数据
		get(url){
			let _this = this
			return new Promise(function(resolve,reject){
				let xhr = new XMLHttpRequest()
				xhr.open("GET",url)
				xhr.onreadystatechange = function(){
					if(xhr.readyState == 4 && xhr.status == 200){
						let parseable = false
						try{
							let res = JSON.parse(xhr.response)
							parseable = true
							resolve(res)
						}catch(err){}
						!parseable && resolve(xhr.response)
						if(++_this.loading >= 5 && !_this.loaded){
							_this.onload()
							_this.loaded = true
						}
					}
				}
				xhr.send(null)
			})
		},
		// 切换主题
		changeTheme(theme){
			e.head.querySelector("#mainTheme").remove()
			e.head.innerHTML += `<link id="mainTheme" rel="stylesheet" type="text/css" href="system/css/${theme}.css"/>`
		}
	}
	w.TOS = TOS
}(document,window)
const os = new TOS()